package wsi.fusion;

import org.rygh.core.xml.XmlPath;
import org.rygh.semantic.model.rdf.Entity;

import wsi.dataguide.tree.WSXmlLeaf;
import wsi.dataguide.tree.WSXmlObject;
import wsi.match.MatchPair;
import wsi.match.SubtreeMatch;
import wsi.subgraph.tree.EntityLeaf;
import wsi.subgraph.tree.EntityTree;

public class FusionTuple {

	private final WSXmlLeaf subroot;
	private final EntityTree entityTree;
	private final EntityLeaf inputNode;
	private final SubtreeMatch subtreeMatch;

	private double probability = -1;// -1 means fuse to input.

	public FusionTuple(WSXmlLeaf subroot, EntityTree entityTree,
			EntityLeaf inputNode, SubtreeMatch subtreeMatch) {
		this.subroot = subroot;
		this.entityTree = entityTree;
		this.inputNode = inputNode;
		this.subtreeMatch = subtreeMatch;
	}

	/**
	 * append the matched entity as a child, for exp 2b.
	 * 
	 * @param value
	 */
	public void appendChild() {
		// check if this subroot has already been appended

		String match_tag = "t:matched_entity";

		for (WSXmlLeaf l : subroot.getChildren())
			if (match_tag.equals(l.getValue().getName())) {
				return;
			}

		Entity entity = inputNode.getValue().getValue();

		WSXmlObject match_obj = new WSXmlObject(match_tag);
		match_obj.addAttribute("t:url", entity.getValue());
		match_obj.addAttribute("t:prob", String.format("%.2f", probability));

		WSXmlLeaf parent = new WSXmlLeaf(subroot, match_obj);

		match_obj = null;
		XmlPath root_xpath = subroot.getXpath();

		for (MatchPair pair : subtreeMatch.getMatchPairs()) {
			EntityLeaf node = pair.getEntityLeaf();
			WSXmlLeaf leaf = pair.getLeft();

			// check if this node is an opposite node w.r.t. center
			if (!node.isChildOf(inputNode))
				continue;

			String xpath = leaf.getXpath().getRelativePathsTo(root_xpath)
					.stripIndex();

			String preds = entityTree.link(inputNode, node).getPredicatePath()
					.getKey();

			match_obj = new WSXmlObject("t:match");
			match_obj.addAttribute("t:xpath", xpath);
			match_obj.addAttribute("t:predicates", preds);
			match_obj
					.addAttribute("t:value_in_xml", leaf.getValue().getValue());
			match_obj.addAttribute("t:value_in_rdf", node.getValue().getValue()
					.getValue());

			new WSXmlLeaf(parent, match_obj);
		}

	}

	public void setProbability(double probability) {
		this.probability = probability;
	}
}
